import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';
import { Form, Input, Button, Radio, Toast, Divider } from '@nutui/nutui-react-taro';
import { Tips } from '@nutui/icons-react-taro';
import './index.scss';
import logo from '../../../assets/logo.svg';
import student from '../../../assets/student.svg';
import leader from '../../../assets/leader.svg';
import { useRoleStore, ROLE_TYPES } from '../../../store/useRoleStore';
import { useInfoStore } from '../../../store/useInfoStore';
import { authApi } from '../../../services/authApi';

const Login = () => {

  const [loading, setLoading] = useState(false);
  const [role, setRole] = useState('student');

  const switchRole = useRoleStore(state => state.switchRole);

  const handleSubmit = async (values) => {
    console.log(values);
    try {
      setLoading(true);
      const data = await authApi.login({
        ...values
      });

      Taro.setStorageSync('token', data);

      // 登录成功后立即获取用户信息
      const userInfo = await authApi.getUserInfo();
      if (userInfo) {
        const setUserInfo = useInfoStore.getState().setInfo;
        const setDomain = useInfoStore.getState().setDomain;
        setUserInfo(userInfo);
        setDomain(userInfo.domain);
      }

      Toast.show({
        title: '登录成功',
        icon: 'success',
      });

      switchRole(role === 'student' ? ROLE_TYPES.STUDENT : ROLE_TYPES.LEADER);

      // 延迟执行跳转，确保 Toast 显示完成
      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/index/index'
        });
      }, 1500);
    } catch (error) {
      console.log(error);
      Toast.show({
        title: '登录失败，请检查用户名和密码',
        icon: 'fail',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <View className="loginContainer">
      <View className="loginBox">
        <View className="logo">
          <Image src={logo} className="logoImage" mode="aspectFit" />
          <View className="title">教育智能OA系统</View>
          <View className="subtitle">学习管理与进度追踪</View>
        </View>

        <Form onFinish={handleSubmit}>
          <View className="input-container">
            <View className="input-title">账号</View>

            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入学号/手机号/邮箱' }]}
            >
              <Input
                className="input"
                placeholder="请输入学号/手机号/邮箱"
              />
            </Form.Item>
          </View>

          <View className="input-container">
            <View className="input-title">密码</View>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input
                className="input"
                type="password"
                placeholder="请输入密码"
              />
            </Form.Item>
          </View>

          <View className="input-container">
            <View className="input-title">角色</View>
            <View className="roleSelect">
              <Radio.Group direction="horizontal" value={role} onChange={val => setRole(val)}>
                <Radio value="student" shape="button"><Image className='roleImage' src={student} /> <View>学生端</View></Radio>
                <Radio value="leader" shape="button"> <Image className='roleImage' src={leader} /> <View>组长端</View></Radio>
              </Radio.Group>
            </View>
            
            {/* 添加提示信息 */}
            <View className="role-tip">
              <Tips color="#2080f0" />
              <Text className="tip-text">组长可以根据需要选择以"学生"或"组长"身份登录</Text>
            </View>
          </View>

          <Form.Item>
            <Button
              style={{ height: '50px', borderRadius: '10px' }}
              color='#2080f0'
              loading={loading}
              type="primary"
              block
              formType="submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </View>
    </View>
  );
};

export default Login;